#include "Mutex.hpp"
int tickets = 1000;
//MutexModule::Mutex gmutex;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
void *ticket(void *arg)
{
    // std::cout<<(char*)arg<<"is buying ticket "<<std::endl;

    while (true)
    {
        {
            MutexModule::LockGuard l(gmutex);
            // 加锁
            // pthread_mutex_lock(&_mutex);
            // gmutex.Lock();
            if (tickets > 0)
            {
                usleep(10000);
                // 买票
                std::cout << "tickets还有:" << tickets << std::endl;
                tickets--;
                // 数据入库
                // usleep(10000);
                // 解锁
                // pthread_mutex_unlock(&_mutex);
                // gmutex.Unlock();
            }
            else
            {
                // gmutex.Unlock();
                // pthread_mutex_unlock(&_mutex);
                break;
            }
        }
    }
    return nullptr;
}

int main()
{
    std::vector<pthread_t> threads;
    for (int i = 1; i <= 4; i++)
    {
        pthread_t tid;
        char buff[64];
        snprintf(buff, sizeof(buff), "thread-%d", i);
        int n = pthread_create(&tid, nullptr, ticket, (void *)buff);
        if (n != 0)
        {
            perror("pthread_create");
            return 1;
        }
        threads.push_back(tid);
        // std::cout<<buff<<" create success"<<std::endl;
    }
    for (auto &thread : threads)
    {
        pthread_join(thread, nullptr);
    }
    return 0;
}